<template>
	<view class="coach">
		<u-navbar :is-back="false">
			<view class="slot-wrap">
				<toggle @change="handleSwitchChange"></toggle>
			</view>
		</u-navbar>
		<!-- 搜索 -->
		<view class="seachbox_s">
			<view class="cityNumber" @click="openProvince" v-if="cityName">
				<text class="size">{{cityName}}</text>
				<u-icon :name="cityShow?'arrow-up':'arrow-down'" color=" #999999" size="14"></u-icon>
			</view>
			<u-search placeholder="搜索门店" :show-action="false" class="search-input" v-model="query.search" :disabled="true"
				@click="routeSeach" v-if="isActive"></u-search>
		</view>
		<!-- 搜索列表 -->
		<scroll-view scroll-y refresher-enabled :refresher-triggered="isRefresher" :style="{ height: 80 + 'vh' }"
			@scrolltolower="scrolltolower" @refresherrefresh="onScrollToUpper" v-if="isActive">
			<!-- 骨架屏 -->
			<skeleton-list v-if="isLoading" :count="5"></skeleton-list>
			<!-- 实际内容 -->
			<smartState v-else :loading="false" :isEmpty="!shopList.length" emptyText="数据">
				<list :seachList="shopList" v-if="shopList.length"></list>
			</smartState>
		</scroll-view>
		<!-- 地图 -->
		<mapbox v-else ref="map" :mapList="shopList" :latitude="latitude" :longitude="longitude" @getlatitude="getLatitude"
			:scale="scale"></mapbox>
		<!-- 切换城市 - 添加动画效果 -->
		<u-popup v-model="cityShow" mode="bottom" width="750rpx" height="1080rpx" :border-radius="16"
			:mask-close-able="false" :duration="300">
			<view class="coupon_pup">
				<view class="header_title">
					<view class="left">
						切换城市
					</view>
					<u-icon name="close" size="34" color="#666666" @click="CityClose"></u-icon>
				</view>
				<view class="location">
					<view class="size56">定位城市</view>
					<view class="right_tab">
						<u-icon name="map" color="#73F0EA" size="30"></u-icon>
						<text class="size57">{{cityNameTwo?cityNameTwo:'未开启定位'}}</text>
					</view>
				</view>
				<view class="flex-box">
					<view class="row-box">
						<scroll-view scroll-y="true" class="scroll-left">
							<view class="left_comlum">
								<view v-for="(item,index) in cityList" :key="index" class="left-Item"
									:class="activeIndex == index ?'color2':'color1'" @click="changeActive(item, index)">
									{{item.title}}
								</view>
							</view>
						</scroll-view>
						<scroll-view scroll-y="true" class="scroll-center">
							<view class="center_comlumn">
								<view v-for="(childItem,childIndex) in cityList[activeIndex].junior" :key="childIndex"
									:class="childActiveIndex == childIndex ?'center-Item-Active':'center-Item'"
									@click="changeChildIndex(childItem,childIndex)">
									{{childItem.title}}
								</view>
							</view>
						</scroll-view>
						<scroll-view scroll-y="true" class="scroll-right">
							<view class="right_comlumn">
								<view v-for="(grandsonItem,grandsonIndex) in cityList[activeIndex].junior[childActiveIndex].junior"
									:key="grandsonIndex" :class="grandsonActiveIndex == grandsonIndex ?'right-Item-Active':'right-Item'"
									@click="changeGrandsonIndex(grandsonItem,grandsonIndex)">
									<text class="left">{{grandsonItem.title}}</text>
									<text>{{grandsonItem.num}}</text>
								</view>
							</view>
						</scroll-view>
					</view>
				</view>
				<view class="bottom">
					<view class="btn" @click="Citysure">
						确认
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import toggle from './components/toggle-button.vue'
	import list from '@/components/general/list.vue'
	import mapbox from './components/map.vue'
	import popupVue from '@/components/popup.vue'
	import empty from '@/components/empty.vue'
	import smartState from '@/components/state.vue';
	import skeletonList from '@/components/SkeletonList.vue';
	import {
		province,
		shopList,
		City
	} from '@/api/shop.js'
	export default {
		components: {
			toggle,
			list,
			mapbox,
			popupVue,
			empty,
			smartState,
			skeletonList
		},
		data() {
			return {
				// 城市选择相关
				cityShow: false,
				activeIndex: 0,
				childActiveIndex: 0,
				grandsonActiveIndex: 0,
				cityList: [],
				query: {
					province: '',
					search: ''
				},
				// 视图切换
				isActive: true, // true: 列表视图, false: 地图视图
				// 门店数据
				shopList: [], // 重命名为更语义化的名称
				cityName: '',
				cityNameTwo: '',
				// 地图定位相关
				latitude: 0,
				longitude: 0,
				scale: 13, // 设置默认缩放级别
				// 加载状态
				isLoading: false,
				// 屏幕信息
				screenHeight: 0,
				navbarHeight: 44, // uView导航栏高度（不包括状态栏）
				statusBarHeight: 0, // 状态栏高度
				searchBoxHeight: 106, // 搜索框高度

				isRefresher: false
			}
		},

		// mounted() {
		// 	uni.onWindowResize(this.onWindowResize);
		// },
		// beforeDestroy() {
		// 	uni.offWindowResize(this.onWindowResize);
		// },
		// 初始化屏幕信息
		// 计算属性 - 动态高度计算
		computed: {
			scrollHeight() {
				if (this.screenHeight > 0) {
					// 精确计算：屏幕高度 - 状态栏 - 导航栏 - 搜索框 - 额外间距
					const totalNavHeight = this.statusBarHeight + this.navbarHeight;
					const dynamicHeight = this.screenHeight - totalNavHeight - this.searchBoxHeight - 20;
					console.log('高度计算:', {
						screenHeight: this.screenHeight,
						statusBarHeight: this.statusBarHeight,
						navbarHeight: this.navbarHeight,
						searchBoxHeight: this.searchBoxHeight,
						dynamicHeight
					});
					return Math.max(dynamicHeight, 300) + 'px'; // 确保最小高度300px
				}
				// 备用方案：使用vh单位，减去估算的固定高度
				return 'calc(100vh - 220rpx)';
			}
		},

		mounted() {
			this.getSystemInfo();
		},

		onShow() {
			this.getLocation()
		},

		methods: {
			// 获取系统信息 - 动态计算高度
			getSystemInfo() {
				const systemInfo = uni.getSystemInfoSync();
				this.screenHeight = systemInfo.windowHeight;
				this.statusBarHeight = systemInfo.statusBarHeight || 0;

				// 获取小程序胶囊按钮信息来计算导航栏高度
				// #ifndef H5
				try {
					const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
					if (menuButtonInfo && menuButtonInfo.height) {
						// 导航栏高度 = 胶囊按钮底部 - 状态栏高度 + 胶囊按钮与状态栏的间距
						this.navbarHeight = (menuButtonInfo.bottom - this.statusBarHeight) + (menuButtonInfo.top - this
							.statusBarHeight);
					}
				} catch (error) {
					console.log('获取胶囊按钮信息失败:', error);
					this.navbarHeight = 44; // 使用默认值
				}
				// #endif

				console.log('屏幕信息:', {
					screenHeight: this.screenHeight,
					statusBarHeight: this.statusBarHeight,
					navbarHeight: this.navbarHeight,
					scrollHeight: this.scrollHeight
				});
			},

			// 处理地图定位变化 - 优化命名
			getLatitude(query) {
				console.log('getLatitude:', query);
				this.latitude = Number(query.lat)
				this.longitude = Number(query.long)
				this.scale = 13
			},

			// 下拉刷新处理 - 添加防抖机制
			async onScrollToUpper() {
				if (this.isLoading) return; // 防止重复请求
				this.isRefresher = true
				uni.showLoading({
					title: '刷新中...'
				});

				try {
					setTimeout(() => {
						this.getLocation()
						uni.hideLoading();
						this.isRefresher = false
					}, 800) // 适当延迟提升体验
				} catch (error) {
					console.error('获取数据失败:', error);
					setTimeout(() => {
						uni.hideLoading();
						uni.showToast({
							title: '获取数据失败',
							icon: 'none'
						});
						this.isRefresher = false
					}, 800)
				}
			},
			// 获取城市信息 - 添加错误处理
			getCity() {
				City().then(({
					data: res
				}) => {
					if (res.code === 1) {
						this.cityNameTwo = res.data.city
					}
				}).catch(error => {
					console.error('获取城市信息失败:', error);
				})
			},

			// 获取门店列表 - 优化命名和错误处理
			getShopList() {
				this.isLoading = true
				shopList(this.query).then(({
					data: res
				}) => {
					console.log('getShopList response:', res);
					if (res.code === 1) {
						this.shopList = res.data.shop_list || []

						// 设置默认地图位置
						if (this.shopList.length > 0) {
							const defaultShop = this.shopList[0]
							this.latitude = Number(defaultShop.lat) || 0
							this.longitude = Number(defaultShop.long) || 0
							this.scale = 13
						}

						this.cityName = res.data.title || ''

						// 如果是地图视图，更新地图数据
						if (!this.isActive && this.$refs.map && this.shopList.length > 0) {
							this.$nextTick(() => {
								this.$refs.map.markers = []
								this.$refs.map.cluster()
								this.$refs.map.toView = 'item-' + this.shopList[0].shop_id
								this.$refs.map.getLabelById = this.shopList[0].shop_id
								this.$refs.map.activeMarkers()
							})
						}
					} else {
						uni.showToast({
							title: res.msg || '获取门店信息失败',
							icon: 'none'
						});
					}
				}).catch(error => {
					console.error('获取门店列表失败:', error);
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					});
				}).finally(() => {
					this.isLoading = false
				})
			},
			// 获取省份城市数据 - 添加错误处理
			getProvince(query) {
				province(query).then(({
					data: res
				}) => {
					console.log('getProvince response:', res);
					if (res.code === 1) {
						this.cityList = res.data || []
					}
				}).catch(error => {
					console.error('获取省份数据失败:', error);
				})
			},

			// 获取定位信息 - 优化错误处理
			getLocation() {
				const that = this;

				uni.getLocation({
					type: "gcj02",
					success(res) {
						console.log('定位成功:', res);
						const {
							latitude,
							longitude
						} = res

						// 存储定位信息
						uni.setStorage({
							key: 'lat',
							data: latitude
						})
						uni.setStorage({
							key: 'long',
							data: longitude
						})

						// 获取相关数据
						that.getCity()
						that.getProvince()
						that.getShopList()
					},
					fail: (error) => {
						console.log('定位失败:', error);
						uni.showToast({
							title: '定位失败，使用默认数据',
							icon: 'none',
							duration: 2000
						});
						// 定位失败也要加载基础数据
						that.getProvince()
						that.getShopList()
					},
				});
			},
			// 城市选择相关方法
			openProvince() {
				this.cityShow = true
			},

			// 关闭城市选择弹窗 - 优化命名
			closeCityPopup() {
				this.cityShow = false
			},

			// 兼容旧版本方法名
			CityClose() {
				this.closeCityPopup()
			},

			// 确认城市选择 - 优化命名和错误处理
			confirmCitySelection() {
				try {
					// 检查是否有有效选择
					if (!this.cityList.length ||
						!this.cityList[this.activeIndex] ||
						!this.cityList[this.activeIndex].junior ||
						!this.cityList[this.activeIndex].junior[this.childActiveIndex] ||
						!this.cityList[this.activeIndex].junior[this.childActiveIndex].junior ||
						!this.cityList[this.activeIndex].junior[this.childActiveIndex].junior[this.grandsonActiveIndex]) {
						uni.showToast({
							title: '请选择完整的城市信息',
							icon: 'none'
						});
						return;
					}

					this.query.province = this.cityList[this.activeIndex]
						.junior[this.childActiveIndex]
						.junior[this.grandsonActiveIndex].province

					this.getShopList()
					this.cityShow = false

					uni.showToast({
						title: '切换成功',
						icon: 'success'
					});
				} catch (error) {
					console.error('确认城市选择失败:', error);
					uni.showToast({
						title: '选择失败，请重试',
						icon: 'none'
					});
				}
			},

			// 兼容旧版本方法名
			Citysure() {
				this.confirmCitySelection()
			},
			// 省市区选择方法 - 移除$forceUpdate优化性能
			changeActive(item, index) {
				this.activeIndex = index
				this.childActiveIndex = 0
				this.grandsonActiveIndex = 0
			},
			changeChildIndex(item, index) {
				this.childActiveIndex = index
				this.grandsonActiveIndex = 0
			},
			changeGrandsonIndex(item, index) {
				console.log('选择区县:', index, item);
				this.grandsonActiveIndex = index
			},

			// 路由跳转 - 优化命名
			routeToSearch() {
				uni.navigateTo({
					url: '/pageA/shop/seach?type=1'
				})
			},

			// 兼容旧版本方法名
			routeSeach() {
				this.routeToSearch()
			},

			// 列表滚动到底部 - 添加日志
			scrolltolower() {
				console.log('列表滚动到底部');
				// TODO: 可以在这里添加分页加载逻辑
			},

			// 视图切换处理 - 优化性能
			handleSwitchChange(isActive) {
				console.log('视图切换:', isActive ? '列表模式' : '地图模式');
				this.isActive = isActive

				// 切换到地图视图时，延迟初始化地图数据以优化性能
				if (!isActive && this.shopList.length > 0) {
					this.$nextTick(() => {
						if (this.$refs.map) {
							try {
								this.$refs.map.markers = []
								this.$refs.map.cluster()
							} catch (error) {
								console.error('地图初始化失败:', error);
							}
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #e9e9e9;
		overflow: hidden;
	}

	.coach {
		display: flex;
		flex-direction: column;
		height: 100vh;

		.slot-wrap {
			margin-left: 32rpx;
		}


	}

	/* 视口高度 */
	.seachbox_s {
		position: relative;
		width: 750rpx;
		height: 106rpx;
		background: #ffffff;
		box-shadow: 0rpx 8rpx 28rpx 0rpx rgba(199, 205, 179, 0.15);
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 0 24rpx 0 40rpx;
		transition: all 0.3s ease;

		.cityNumber {
			flex: 1;
			display: flex;
			flex-direction: row;
			align-items: center;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			padding: 10rpx 0;
			border-radius: 16rpx;
			transition: all 0.2s ease;

			&:active {
				background: #f5f5f5;
			}

			.size {
				margin-right: 7rpx;
				font-size: 28rpx;
				font-family: PingFang SC, PingFang SC-Medium;
				font-weight: 500;
				color: #333333;
			}

		}

		.search-input {
			/* 基础样式 */
			position: absolute;
			right: 24rpx;
			width: 204rpx;
			height: 66rpx;
			background: #f6f6f6;
			border-radius: 16rpx;
			transition: width 0.3s ease, background 0.3s ease;
			/* 宽度变化的过渡效果 */

			&:active {
				background: #eeeeee;
			}
		}

	}

	.coupon_pup {
		width: 750rpx;
		height: 1080rpx;
		border-radius: 16rpx 16rpx 0 0;

		.header_title {
			padding: 30rpx;
			display: flex;
			flex-direction: row;
			align-items: center;

			.left {
				font-size: 36rpx;
				font-family: PingFang SC, PingFang SC-Bold;
				font-weight: 700;
				text-align: left;
				color: #333333;
				flex: 1;
			}
		}

		.location {
			padding-left: 30rpx;
			display: flex;
			flex-direction: row;
			align-items: center;
			margin-bottom: 28rpx;

			.size56 {
				margin-right: 20rpx;
				font-size: 28rpx;
				font-family: PingFang SC, PingFang SC-Medium;
				font-weight: 500;
				text-align: left;
				color: #666666;
			}

			.right_tab {
				display: flex;
				flex-direction: row;
				align-items: center;

				.size57 {
					font-size: 28rpx;
					font-family: PingFang SC, PingFang SC-Medium;
					font-weight: 500;
					text-align: left;
					color: #73F0EA;
				}
			}
		}

		.flex-box {
			width: 100%;
			height: 51vh;
		}

		.bottom {
			width: 100%;
			height: 164rpx;
			padding-top: 24rpx;
			display: flex;
			justify-content: center;
			background: #ffffff;
			position: fixed;
			bottom: 0;

			.btn {
				width: 710rpx;
				height: 88rpx;
				background: #73F0EA;
				border-radius: 16rpx;
				font-size: 34rpx;
				font-family: PingFang SC, PingFang SC-Bold;
				font-weight: 700;
				color: #ffffff;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	.row-box {
		display: flex;
		flex-direction: row;
		align-items: center;
		width: 100%;
		height: 100%;

		.scroll-left {
			width: 196rpx;
			background: #f8f8f8;
			height: 100%;

			.left_comlum {
				width: 100%;
				display: flex;
				flex-direction: column;
				align-items: center;

				.left-Item {
					width: 100%;
					padding: 20rpx 0;
					font-size: 28rpx;
					font-family: PingFang SC, PingFang SC-Medium;
					font-weight: 500;
					text-align: left;

					display: flex;
					align-items: center;
					justify-content: center;
				}

				.color1 {
					color: #666666;
				}

				.color2 {
					color: #73F0EA;
				}
			}
		}

		.scroll-center {
			width: 210rpx;
			height: 100%;
			border-right: 1rpx solid #e9e9e9;
			background-color: #ffffff;

			.center_comlumn {
				width: 100%;
				display: flex;
				flex-direction: column;
				align-items: center;

				.center-Item {
					width: 200rpx;
					height: 80rpx;
					background: #ffffff;
					border-radius: 16rpx;
					font-size: 28rpx;
					font-family: PingFang SC, PingFang SC-Medium;
					font-weight: 500;
					color: #666666;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-bottom: 8rpx;
				}

				.center-Item-Active {
					background-color: rgba(129, 202, 197, 0.1);
					width: 200rpx;
					height: 80rpx;
					border-radius: 16rpx;
					font-size: 28rpx;
					font-family: PingFang SC, PingFang SC-Medium;
					font-weight: 500;
					color: #73F0EA;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-bottom: 8rpx;
				}
			}
		}

		.scroll-right {
			flex: 1;
			height: 100%;
			background-color: #ffffff;

			.right_comlumn {
				width: 100%;
				display: flex;
				flex-direction: column;
				align-items: center;

				.left {
					flex: 1;
				}

				.right-Item {
					width: 330rpx;
					height: 80rpx;
					background: #ffffff;
					border-radius: 16rpx;
					font-size: 28rpx;
					font-family: PingFang SC, PingFang SC-Medium;
					font-weight: 500;
					color: #666666;
					display: flex;
					flex-direction: row;
					align-items: center;
					padding: 0 26rpx;
					margin-bottom: 8rpx;
				}

				.right-Item-Active {
					background-color: rgba(129, 202, 197, 0.1);
					width: 330rpx;
					height: 80rpx;
					border-radius: 16rpx;
					font-size: 28rpx;
					font-family: PingFang SC, PingFang SC-Medium;
					font-weight: 500;
					color: #73F0EA;
					display: flex;
					flex-direction: row;
					align-items: center;
					padding: 0 26rpx;
					margin-bottom: 8rpx;
				}
			}
		}
	}
</style>